package controllers

import (
	"awesomeProject/models"
	"awesomeProject/views"
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

// ComponentController 处理组件相关操作。
type ComponentController struct {
	templates  *views.Templates
	collection *mongo.Collection
}

// NewComponentController 创建一个新的 ComponentController 实例。
func NewComponentController(templates *views.Templates, collection *mongo.Collection) *ComponentController {
	return &ComponentController{
		templates:  templates,
		collection: collection,
	}
}

// StartServer 启动 HTTP 服务器并注册路由。
func (cc *ComponentController) StartServer() {
	router := gin.Default()

	router.GET("/components", cc.ListComponents)
	router.GET("/components/:id", cc.GetComponent)
	router.POST("/components", cc.CreateComponent)
	router.PUT("/components/:id", cc.UpdateComponent)
	router.DELETE("/components/:id", cc.DeleteComponent)

	router.Run(":8000")
}

// ListComponents 返回所有组件的列表。
func (cc *ComponentController) ListComponents(c *gin.Context) {
	// 使用查询语句获取所有组件信息
	results, err := models.FindWithSelect02(cc.collection, bson.M{})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	cc.templates.Render(c, http.StatusOK, "components.html", gin.H{"components": results})
}

// GetComponent 获取单个组件信息。
func (cc *ComponentController) GetComponent(c *gin.Context) {
	id := c.Param("id")
	componentID, err := strconv.ParseUint(id, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的组件ID"})
		return
	}

	// 使用查询语句获取单个组件信息
	results, err := models.FindWithSelect02(cc.collection, bson.M{"_id": componentID})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "组件不存在"})
		return
	}

	if len(results) == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "组件不存在"})
		return
	}

	c.JSON(http.StatusOK, results[0])
}

// CreateComponent 创建新组件。
func (cc *ComponentController) CreateComponent(c *gin.Context) {
	var component models.Component
	if err := c.ShouldBindJSON(&component); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 将组件数据转换为 JSON 字符串
	jsonData, err := json.Marshal(component)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "JSON 序列化失败"})
		return
	}

	// 插入组件数据到 MongoDB
	err = models.InsertPersonV2(cc.collection, string(jsonData))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, component)
}

// UpdateComponent 更新组件信息。
func (cc *ComponentController) UpdateComponent(c *gin.Context) {
	id := c.Param("id")
	componentID, err := strconv.ParseUint(id, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的组件ID"})
		return
	}

	var component models.Component
	if err := c.ShouldBindJSON(&component); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 将组件数据转换为 JSON 字符串
	jsonData, err := json.Marshal(component)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "JSON 序列化失败"})
		return
	}

	// 更新组件数据到 MongoDB
	err = models.UpdateDataV2(cc.collection, "_id", strconv.FormatUint(componentID, 10), "data", string(jsonData))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, component)
}

// DeleteComponent 删除组件。
func (cc *ComponentController) DeleteComponent(c *gin.Context) {
	id := c.Param("id")
	componentID, err := strconv.ParseUint(id, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的组件ID"})
		return
	}

	// 删除组件数据从 MongoDB
	err = models.DeleteDataV2(cc.collection, "_id", strconv.FormatUint(componentID, 10))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "组件已成功删除"})
}
